package com.itheima.reggie.controller;

import com.itheima.reggie.commons.R;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;
@Api(tags ="上传下载")
@RestController
@RequestMapping("/common")
public class CommonController  extends BaseController{

    //上传文件目录
    @Value("${reggie.path}")
    private String imgPath;

    /**
     * 上传文件
     * MultipartFile方法的参数名：必须与表单文件域的名字一样
     * @return 返回上传的文件名
     */
    @SneakyThrows
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) {
        //1.获取原始的文件名
        String filename = file.getOriginalFilename();
        String picFile="";
        if (filename!=null) {
            //2.修改上传的文件名
            //2.1获取后缀名 (从点号的位置开始，取子字符串到最后)
            String suffix = filename.substring(filename.lastIndexOf("."));
            //.jpg
            //2.2生成主文件名 + 后缀名
            picFile = UUID.randomUUID() + suffix;
            //3.上传文件
            file.transferTo(new File(imgPath, picFile));
        }

        //目录，文件名
        //4.返回上传的文件名
        return R.success(picFile);
    }
    @SneakyThrows
    @GetMapping("download")
    public void download(String name){
        FileInputStream fileInputStream = new FileInputStream(imgPath + name);
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(fileInputStream, outputStream);
        fileInputStream.close();
        outputStream.close();
    }
}
